"""
学生信息管理视图
"""
from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db.models import Q, Count
from django.shortcuts import get_object_or_404
from django.contrib.auth import get_user_model
from openpyxl import load_workbook
from accounts.permissions import IsAdminUser, IsTeacherOrAdmin

User = get_user_model()
from .models import School, Major, Grade, Student, TeacherStudentAssignment
from .serializers import (
    SchoolSerializer, MajorSerializer, GradeSerializer,
    StudentSerializer, StudentCreateSerializer, StudentUpdateSerializer,
    StudentBatchCreateSerializer, TeacherStudentAssignmentSerializer,
    StudentStatisticsSerializer, StudentImportSerializer
)


# 校区管理视图
class SchoolListCreateView(generics.ListCreateAPIView):
    """校区列表和创建"""

    queryset = School.objects.all()
    serializer_class = SchoolSerializer
    permission_classes = [IsTeacherOrAdmin]  # 允许教师和管理员访问
    filterset_fields = ['is_active']
    search_fields = ['name', 'code', 'principal']
    ordering_fields = ['name', 'created_at']
    ordering = ['name']

    def get_permissions(self):
        """根据请求方法设置权限"""
        if self.request.method == 'GET':
            # GET请求（获取列表）允许教师和管理员
            return [IsTeacherOrAdmin()]
        else:
            # POST请求（创建）只允许管理员
            return [IsAdminUser()]


class SchoolDetailView(generics.RetrieveUpdateDestroyAPIView):
    """学校详情、更新和删除"""
    
    queryset = School.objects.all()
    serializer_class = SchoolSerializer
    permission_classes = [IsAdminUser]


# 专业管理视图
class MajorListCreateView(generics.ListCreateAPIView):
    """专业列表和创建"""

    queryset = Major.objects.all()
    serializer_class = MajorSerializer
    permission_classes = [IsTeacherOrAdmin]
    filterset_fields = ['is_active']
    search_fields = ['name']
    ordering_fields = ['name', 'created_at']
    ordering = ['name']


class MajorDetailView(generics.RetrieveUpdateDestroyAPIView):
    """专业详情、更新和删除"""

    queryset = Major.objects.all()
    serializer_class = MajorSerializer
    permission_classes = [IsTeacherOrAdmin]


# 年级管理视图
class GradeListCreateView(generics.ListCreateAPIView):
    """年级列表和创建"""

    queryset = Grade.objects.all()
    serializer_class = GradeSerializer
    permission_classes = [IsTeacherOrAdmin]
    filterset_fields = ['is_active']
    search_fields = ['name']
    ordering_fields = ['name', 'created_at']
    ordering = ['name']


class GradeDetailView(generics.RetrieveUpdateDestroyAPIView):
    """年级详情、更新和删除"""

    queryset = Grade.objects.all()
    serializer_class = GradeSerializer
    permission_classes = [IsTeacherOrAdmin]




# 学生管理视图
class StudentListCreateView(generics.ListCreateAPIView):
    """学生列表和创建"""

    permission_classes = [IsTeacherOrAdmin]
    filterset_fields = [
        'grade', 'gender', 'status', 'employment_status', 'resume_status'
    ]
    search_fields = ['student_id', 'name', 'phone', 'email']
    ordering_fields = ['student_id', 'name', 'created_at']
    ordering = ['student_id']

    def get_queryset(self):
        return Student.objects.select_related('grade', 'user').all()

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return StudentCreateSerializer
        return StudentSerializer


class StudentDetailView(generics.RetrieveUpdateDestroyAPIView):
    """学生详情、更新和删除"""

    permission_classes = [IsTeacherOrAdmin]

    def get_queryset(self):
        return Student.objects.select_related('grade', 'user').all()

    def get_serializer_class(self):
        if self.request.method in ['PUT', 'PATCH']:
            return StudentUpdateSerializer
        return StudentSerializer


@api_view(['POST'])
@permission_classes([IsAdminUser])
def batch_create_students(request):
    """批量创建学生"""
    serializer = StudentBatchCreateSerializer(data=request.data)
    if serializer.is_valid():
        result = serializer.save()
        return Response(result, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAdminUser])
def import_students(request):
    """从Excel导入学生"""
    serializer = StudentImportSerializer(data=request.data)
    if serializer.is_valid():
        file = serializer.validated_data['file']
        
        try:
            workbook = load_workbook(file)
            worksheet = workbook.active
            
            students_data = []
            errors = []
            
            # 跳过标题行
            for row_num, row in enumerate(worksheet.iter_rows(min_row=2, values_only=True), start=2):
                if not any(row):  # 跳过空行
                    continue
                
                try:
                    student_data = {
                        'student_id': row[0],
                        'name': row[1],
                        'gender': row[2],
                        'grade': row[3],  # 需要根据年级名称查找年级ID
                        'phone': row[4],
                        'email': row[5],
                        'status': 'active',
                        'employment_status': 'unemployed',
                        'resume_status': 'not_started'
                    }

                    # 查找年级
                    try:
                        grade_obj = Grade.objects.get(name=row[3])
                        student_data['grade'] = grade_obj.id
                    except Grade.DoesNotExist:
                        errors.append({
                            'row': row_num,
                            'student_id': row[0],
                            'error': f'年级 {row[3]} 不存在'
                        })
                        continue
                    
                    students_data.append(student_data)
                    
                except Exception as e:
                    errors.append({
                        'row': row_num,
                        'student_id': row[0] if row[0] else 'Unknown',
                        'error': str(e)
                    })
            
            # 批量创建学生
            if students_data:
                batch_serializer = StudentBatchCreateSerializer(data={'students': students_data})
                if batch_serializer.is_valid():
                    result = batch_serializer.save()
                    result['import_errors'] = errors
                    return Response(result, status=status.HTTP_201_CREATED)
                else:
                    return Response({
                        'errors': batch_serializer.errors,
                        'import_errors': errors
                    }, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({
                    'message': '没有有效的学生数据',
                    'import_errors': errors
                }, status=status.HTTP_400_BAD_REQUEST)
                
        except Exception as e:
            return Response({
                'error': f'文件处理失败: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 师生分配关系管理
class TeacherStudentAssignmentListCreateView(generics.ListCreateAPIView):
    """师生分配关系列表和创建"""
    
    queryset = TeacherStudentAssignment.objects.select_related('teacher', 'student').all()
    serializer_class = TeacherStudentAssignmentSerializer
    permission_classes = [IsAdminUser]
    filterset_fields = ['teacher', 'student', 'assignment_type', 'is_active']
    ordering = ['-assigned_date']


class TeacherStudentAssignmentDetailView(generics.RetrieveUpdateDestroyAPIView):
    """师生分配关系详情、更新和删除"""
    
    queryset = TeacherStudentAssignment.objects.select_related('teacher', 'student').all()
    serializer_class = TeacherStudentAssignmentSerializer
    permission_classes = [IsAdminUser]


@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def student_statistics(request):
    """学生统计"""
    user = request.user
    
    # 基础查询集
    queryset = Student.objects.all()
    
    # 基础统计
    total_students = queryset.count()
    active_students = queryset.filter(status='active').count()
    graduated_students = queryset.filter(status='graduated').count()
    employed_students = queryset.filter(employment_status='employed').count()
    
    # 计算就业率
    employment_rate = (employed_students / graduated_students * 100) if graduated_students > 0 else 0
    
    # 简历统计
    resume_completed = queryset.filter(resume_status='approved').count()
    resume_completion_rate = (resume_completed / total_students * 100) if total_students > 0 else 0
    
    # 面试统计
    interview_participated = queryset.filter(interview_count__gt=0).count()
    
    # 按年级统计
    by_grade = queryset.values('grade__name').annotate(count=Count('id'))
    
    # 按就业状态统计
    by_employment_status = queryset.values('employment_status').annotate(count=Count('id'))
    
    # 按简历状态统计
    by_resume_status = queryset.values('resume_status').annotate(count=Count('id'))
    
    data = {
        'total_students': total_students,
        'active_students': active_students,
        'graduated_students': graduated_students,
        'employed_students': employed_students,
        'employment_rate': round(employment_rate, 2),
        'resume_completed': resume_completed,
        'resume_completion_rate': round(resume_completion_rate, 2),
        'interview_participated': interview_participated,
        'by_grade': {item['grade__name']: item['count'] for item in by_grade},
        'by_employment_status': {item['employment_status']: item['count'] for item in by_employment_status},
        'by_resume_status': {item['resume_status']: item['count'] for item in by_resume_status},
    }
    
    serializer = StudentStatisticsSerializer(data)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def my_students(request):
    """获取我负责的学生"""
    user = request.user

    if user.role == 'teacher':
        # 老师只能看到自己负责的学生
        students = Student.objects.filter(advisor=user).select_related('grade')
    else:
        # 管理员可以看到所有学生
        students = Student.objects.select_related('grade').all()

    serializer = StudentSerializer(students, many=True)
    return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAdminUser])
def assign_advisor(request):
    """管理员为学生分配指导老师"""
    try:
        student_id = request.data.get('student_id')
        advisor_id = request.data.get('advisor_id')

        if not student_id:
            return Response({'error': '学生ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取学生
        try:
            student = Student.objects.get(id=student_id)
        except Student.DoesNotExist:
            return Response({'error': '学生不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 处理指导老师
        advisor = None
        if advisor_id:
            try:
                from accounts.models import User
                advisor = User.objects.get(id=advisor_id, role='teacher')
            except User.DoesNotExist:
                return Response({'error': '指导老师不存在或不是老师角色'}, status=status.HTTP_404_NOT_FOUND)

        # 更新学生的指导老师
        old_advisor = student.advisor
        student.advisor = advisor
        student.save()

        # 构建响应消息
        if advisor:
            message = f'已为学生 {student.name} 分配指导老师：{advisor.username}'
        else:
            message = f'已取消学生 {student.name} 的指导老师分配'

        return Response({
            'message': message,
            'student_id': student.id,
            'student_name': student.name,
            'old_advisor': old_advisor.username if old_advisor else None,
            'new_advisor': advisor.username if advisor else None
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAdminUser])
def batch_assign_advisor(request):
    """批量为学生分配指导老师"""
    try:
        assignments = request.data.get('assignments', [])

        if not assignments:
            return Response({'error': '分配列表不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        success_count = 0
        error_list = []

        for assignment in assignments:
            student_id = assignment.get('student_id')
            advisor_id = assignment.get('advisor_id')

            try:
                # 获取学生
                student = Student.objects.get(id=student_id)

                # 获取指导老师
                advisor = None
                if advisor_id:
                    from accounts.models import User
                    advisor = User.objects.get(id=advisor_id, role='teacher')

                # 更新分配
                student.advisor = advisor
                student.save()
                success_count += 1

            except Student.DoesNotExist:
                error_list.append(f'学生ID {student_id} 不存在')
            except User.DoesNotExist:
                error_list.append(f'老师ID {advisor_id} 不存在或不是老师角色')
            except Exception as e:
                error_list.append(f'学生ID {student_id} 分配失败：{str(e)}')

        return Response({
            'message': f'批量分配完成，成功：{success_count}，失败：{len(error_list)}',
            'success_count': success_count,
            'error_count': len(error_list),
            'errors': error_list
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAdminUser])
def advisor_statistics(request):
    """获取指导老师统计信息"""
    try:
        from accounts.models import User
        from django.db.models import Count

        # 获取所有老师及其负责的学生数量
        teachers = User.objects.filter(role='teacher').annotate(
            student_count=Count('student_set')
        ).values('id', 'username', 'first_name', 'last_name', 'student_count')

        # 获取未分配指导老师的学生数量
        unassigned_count = Student.objects.filter(advisor__isnull=True).count()

        return Response({
            'teachers': list(teachers),
            'unassigned_students': unassigned_count,
            'total_teachers': len(teachers)
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def teacher_list(request):
    """获取教师列表（用于下拉框）"""
    try:
        teachers = User.objects.filter(
            role='teacher',
            is_active=True
        ).values('id', 'username', 'first_name', 'last_name').order_by('username')

        return Response(list(teachers))
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
